﻿/// <reference path="../jquery-1.10.2.min.js" />

(function ($) {
    $.loadJs = function (url, callback, callbackParams) {
        /// <summary>加载js文件</summary>
        /// <param name="url" type="String">js文件的url路径</param>
        /// <param name="callback" type="String">加载完毕之后回调的方法</param>
        /// <param name="callbackParams" type="Object">传入给回调方法的参数</param>
        var script = $.getJsObject(url);
        if (script != null) {
            if (callback) {
                callback.call(script, callbackParams);
            }
        }
        else {
            var done = false;
            script = document.createElement('script');
            script.type = 'text/javascript';
            script.language = 'javascript';
            script.src = url;
            script.onload = script.onreadystatechange = function () {
                if (!done && (!script.readyState || script.readyState == 'loaded' || script.readyState == 'complete')) {
                    done = true;
                    script.onload = script.onreadystatechange = null;
                    if (callback) {
                        callback.call(script, callbackParams);
                    }
                }
            }
            document.getElementsByTagName("head")[0].appendChild(script);
        }
    };

    $.getJsObject = function (url) {
        /// <summary>根据url获取js对象</summary>
        /// <param name="url" type="String">js文件的url地址</param>
        var scripts = document.getElementsByTagName("script");
        if (scripts && scripts.length > 0) {
            for (var i = 0; i < scripts.length; i++) {
                if (scripts[0].src === url) return scripts[0];
            }
        }
        return null;
    };

    $.hasLoadJs = function (url) {
        /// <summary>判断指定url的js是否被加载了</summary>
        /// <param name="url" type="String">需要判断的js文件的url地址</param>
        var script = $.getJsObject(url);
        return script != null;
    };

    $.runJs = function (url, callback) {
        /// <summary>加载js文件，并自动执行里面的代码（类似JQ的写法），执行完毕之后删除此js文件</summary>
        /// <param name="url" type="String">js文件的url路径</param>
        /// <param name="callback" type="String">加载完毕之后回调的方法</param>
        loadJs(url, function () {
            document.getElementsByTagName("head")[0].removeChild(this);
            if (callback) {
                callback();
            }
        });
    };

    $.loadCss = function (url, callback) {
        /// <summary>加载css文件</summary>
        /// <param name="url" type="String">css文件的url路径</param>
        /// <param name="callback" type="String">加载完毕之后回调的js方法</param>
        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.media = 'screen';
        link.href = url;
        document.getElementsByTagName('head')[0].appendChild(link);
        if (callback) {
            callback.call(link);
        }
    };
})(jQuery);